const userInfoController = require('./user-info');
const liveInfoService = require('../services/live-info');
const liveCode = require('../codes/live');

module.exports = {

	/**
	 * 获取在线直播信息
	 * @param  {obejct} ctx 上下文对象
	 */
	async getLiveInfo(ctx) {
		let formData = ctx.request.query;
		let queryObj = {
			'page_number': formData.page_number,
			'page_size': formData.page_size
		};
		let result = {
			success: false,
			message: '直播信息获取失败',
			data: null,
			code: ''
		};
		if(formData.user_id) {
			queryObj.user_id = formData.user_id;
		}
		if(formData.is_live) {
			queryObj.is_live = formData.is_live;
		}

		let liveResult = await liveInfoService.getLiveInfo(queryObj);
		if(liveResult) {
			result.success = true;
			result.data = liveResult;
			result.message = '直播信息获取成功';
		}

		ctx.body = result;
	},

	/**
	 * 创建用户直播信息
	 * @param  {obejct} ctx 上下文对象
	 */
	async createLiveInfo(ctx) {
		let formData = ctx.request.body;
		let createObj = {
			'user_id': formData.user_id,
			'name': formData.name,
			'title': formData.title,
			'room_id': formData.room_id,
			'cover': formData.cover,
			'viewing_number': formData.viewing_number,
			'is_live': formData.is_live,
			'category_id': formData.category_id
		};
		let result = {
			success: false,
			message: '直播信息增加失败',
			data: null,
			code: ''
		};
		for(let key in createObj) {
			if(!formData.key) {
				ctx.status = 500;
				ctx.body = `参数${key}不能为空`;
				return;
			}
		}
		createObj.create_time = new Date().getTime();
		createObj.update_time = new Date().getTime();

		let liveResult = await liveInfoService.createLiveInfo(createObj);
		if(liveResult) {
			result.success = true;
			result.data = liveResult;
			result.message = '直播信息增加成功';
		}

		ctx.body = result;
	},

	/**
	 * 更新用户直播信息
	 * @param  {obejct} ctx 上下文对象
	 */
	async updateLiveInfo(ctx) {
		let formData = ctx.request.body;
		let updateSqlObj = {};
		let userId = formData.user_id;
		let result = {
			success: false,
			message: '直播信息更新失败',
			data: null,
			code: ''
		};
		updateSqlObj = {
			'name': formData.name,
			'title': formData.title,
			'room_id': formData.room_id,
			'cover': formData.cover,
			'viewing_number': formData.viewing_number,
			'is_live': formData.is_live,
			'category_id': formData.category_id,
		}
		for(let key in updateSqlObj) {
			if(!updateSqlObj[key]) {
				delete updateSqlObj[key];
			}
		}

		let liveResult = await liveInfoService.updateLiveInfo(updateSqlObj, userId);
		if(liveResult) {
			result.success = true;
			result.data = liveResult;
			result.message = '直播信息更新成功';
		}

		ctx.body = result;
	},

};